
/*
 * GET home page.
 */
var crypto=require('crypto');
var fs = require('fs');
var User=require('../models/user');         //前台用户
var Page=require('../models/page');
var Reply=require('../models/reply');
var BbsPlate=require('../models/bbsPlate');
var Active=require('../models/avtive');
var LoveActive=require('../models/loveActive');
var Post=require('../models/post');
var Relative=require('../models/relative');
var ActiveToPost=require('../models/activeToPost');
var Calendar=require('../models/calendar');
var Province=require('../models/province');
var City=require('../models/city');
var Area=require('../models/area');
var Coffee=require('../models/coffee');
var OrderRecord=require('../models/orderRecord');
var OrderReply=require('../models/orderReply');
var ActiveApply=require('../models/activeApply');
var Dynimic=require('../models/dynimic');
var DynimicReply=require('../models/dynimicReply');
var SecondReply=require('../models/secondReply');
var nodemailer = require("nodemailer");
var dateFormat = require('dateformat');
var async=require('async');
 module.exports = function(app) {
     app.get('/z', function (req, res) {
         //req.setLocale('zh-CN');
         req.session.language='zh-CN';
         res.redirect('back');
     })
     app.get('/u', function (req, res) {
         //req.setLocale('en-US');
         req.session.language='en-US';
         res.redirect('back');
     })
     app.get('/', function (req, res) {
//        var language=req.headers['accept-language'].split(',')[0];
//        var a=language.charAt(language.length-2).toUpperCase();
//        language.replace(language.charAt(language.length-2),a);
//        console.log(req.getLocale());
//        console.log(a);
//        console.log(language);
//        //req.setLocale('zh-cn');
//        console.log(req.getLocale());
//        //console.log(res.__('a').a);
         res.render('login', { title: res.__('reg').login, menu: ''});
     });

     app.get('/reg', function (req, res) {
         res.render('reg', {
             title: res.__('title').reg,
             menu: ''
         });
     });
     //app.get('/reg', checkNotLogin);
     app.post('/reg', function (req, res) {
         //检验用户两次输入的口令是否一致
//         if (req.body['password-repeat'] != req.body['password']) {
//             req.flash('error', '两次输入的口令不一致');
//             return res.redirect('/reg');
//         }
         //生成口令的散列值
         var md5 = crypto.createHash('md5');
         var password = md5.update(req.body.password).digest('base64');
         var newUser = new User({
             username: req.body.username,
             password: password,
             gender: req.body.gender,
             age: req.body.age,
             nickname: req.body.nickname,
             email:req.body.email
         });
         if(req.body.gender==1){
             newUser.headSrc='/images/head_img/man.jpg'
         }else{
             newUser.headSrc='/images/head_img/woman.jpg'
         }

         //检查用户名是否已经存在
         newUser.findUserByName(newUser.username, function (err, doc) {
             if (doc)
                 err = res.__('warn').haveuser;
             if (err) {
                 req.flash('error', err);
                 return res.redirect('/reg');
             }
             //如果不存在则新增用户
             newUser.save(function (err, doc) {
                 if (err) {
                     req.flash('error', err);
                     return res.redirect('/reg');
                 }

                 req.session.user = doc;
                 req.flash('success', res.__('warn').s_reg);
                 res.redirect('/findPartner');
             });

         });
     });
     app.post('/login', function (req, res) {
         var username = req.body.username;
         var md5 = crypto.createHash('md5');
         var password = md5.update(req.body.password).digest('base64');
         var user = new User();
         user.findUserByName(username, function (err, doc) {
             if (!doc) {
                 req.flash('error', res.__('warn').n_user);
                 return res.redirect('/');
             }
             if (doc.password != password) {
                 req.flash('error', res.__('warn').e_pwd);
                 return res.redirect('/');
             }
             req.session.user =doc;
             req.flash('success', res.__('warn').s_login);
             res.redirect('/findPartner');


         })

     });

     app.get('/logout', function (req, res) {
         req.session.user = null;
         req.flash('success', res.__('warn').s_loginout);
         res.redirect('/');
     });
     app.get('/mySchedule', function (req, res) {
         new Calendar().findCalendarByOpt({user: req.session.user._id}, function (err,datas) {
             if (err) {
                 req.flash('error', err);
                 return res.redirect('back');
             }
             res.render('mySchedule', {
                 title: '日程管理',
                 datas: datas,
                 menu: ''
             });
         })
     });
     app.get('/orderPartner',function(req,res){
         var options = {'$or': [
             {applyUser: req.session.user._id},
             {respondentUser: req.session.user._id}
         ], applyFlag: 1};
         var keyword = 'applyUser respondentUser';
         var docs = [];
         var page = new Page(req.query.num);
         var obj = {
             page: page,
             search: options
         };
         new Relative().findForPage(obj,keyword,function (err,count, pageCount, datas) {
             if (err) {
                 req.flash('error', err);
                 return res.redirect('back');
             }
             if (datas) {
                 datas.forEach(function (data, index) {
                     if (req.session.user._id == data.applyUser._id) {
                         docs.push(data.respondentUser);
                     } else {
                         docs.push(data.applyUser);
                     }
                 })
             }
             //为数组添加数据去重的方法
             Array.prototype.distinct = function () {
                 var a = [], b = [];
                 for (var prop in this) {
                     var d = this[prop];
                     if (d === a[prop]) continue; //防止循环到prototype
                     if (b[d] != 1) {
                         a.push(d);
                         b[d] = 1;
                     }
                 }
                 return a;
             }
             docs = docs.distinct();//数据去重
             page.pageCount = pageCount;
             res.render('orderPartner', {
                 title: '我的语伴',
                 datas: docs,
                 page: page,
                 menu: ''
             });
         })
     })
     app.get('/partnerSchedule', function (req, res) {
         var options={start:{$gte:req.query.start,$lte:req.query.end},user: req.query.id}
         new Calendar().findCalendarByOpt(options,function(err,datas){
             console.log(datas.length);
             res.render('json',{
                 datas:datas
             });
//             var str="[{title:'测试',start:'2014-09-24}]";
//             res.end(str);
         })
     });
     app.get('/orderForm',function(req,res){
         new Province().findAllProvince(function(err,datas){
             if(err){
                 return res.end(err);
             }
             new Coffee().findCoffeeByOpt({state:0},function(err,coffeeDatas){
                 if(err){
                     return res.end(err);
                 }
                 res.render('orderForm',{
                     datas:datas,
                     coffeeDatas:coffeeDatas,
                     _id:req.query._id
                 })
             })

         })
     })
     app.post('/filterCoffee',function(req,res){
         var options={};
         if(req.body.province!=''){
             options.province=req.body.province;
         }
         if(req.body.area!=''){
             options.area=req.body.area;
         }
         if(req.body.city!=''){
             options.city=req.body.city;
         }
         new Coffee().findCoffeeByOpt(options,function(err,datas){
             if(err){
                 return res.end('1')
             }
             res.render('filterData',{
                 coffeeDatas:datas
             })
         })

     })
     app.get('/dialogMessage',function(req,res){
         new Calendar().findCalendarById(req.query.calendarId,function(err,calendarData){
             if(err){
                 return res.end(res.__('warn').e_data)
             }
             var start=calendarData.start;
             if(start.indexOf('T')>0){
                 start=start.replace(/T/g,' ');
                 start=dateFormat(new Date(start),'m.dd号(dddd) hh:MM')
             }else{
                 start=dateFormat(new Date(start),'m.dd号(dddd)')
             }
             if(req.getLocale()=='zh-CN'){
                 start=start.replace(/Saturday/g,'周六');
                 start=start.replace(/Sunday/g,'周日');
                 start=start.replace(/Monday/g,'周一');
                 start=start.replace(/Tuesday/g,'周二');
                 start=start.replace(/Wednesday/g,'周三');
                 start=start.replace(/Thursday/g,'周四');
                 start=start.replace(/Friday/g,'周五');
             }
             calendarData.start=start;
             new Coffee().findCoffeeByOpt({_id:req.query.coffeeId},function(err,coffeeData){
                 if(err){
                     return res.end(res.__('warn').e_data)
                 }
                 res.render('dialogMessage',{
                     calendarData:calendarData,
                     coffeeData:coffeeData[0]
                 })
             })
         })
     })
     app.get('/loadCity',function(req,res){
         if(req.query.pid==""){
             var datas=[];
             res.render('loadData',{
                 datas:datas
             })
         }else{
             new City().findCityByPid(req.query.pid,function(err,datas){
                 if(err){
                     console.log(err)
                 }
                 res.render('loadData',{
                     datas:datas
                 })
             })
         }

     })
     app.get('/loadArea',function(req,res){
         if(req.query.cid==""){
             var datas=[];
             res.render('loadData',{
                 datas:datas
             })

         }else{
             new Area().findAreaByCid(req.query.cid,function(err,datas){
                 if(err){
                     console.log(err)
                 }
                 res.render('loadData',{
                     datas:datas
                 })
             })
         }

     })
     app.all('/orderCalendar',function(req,res){
         var options={orderUser:req.session.user._id,orderCalendar:req.query.orderCalendar};
         var orderRecord=new OrderRecord();
         orderRecord.orderUser=req.session.user._id;
         orderRecord.orderCalendar=req.query.orderCalendar;
         orderRecord.orderCoffee=req.query.orderCoffee;
         async.waterfall([
             function(callback){
                 new Calendar().findCalendarById(req.query.orderCalendar,function(err,calendarDate){

                     callback(err, calendarDate);
                 })
             },
             function(calendarDate, callback){
                 orderRecord.orderToUser=calendarDate.user;
                 orderRecord.findOrderRecordByOptions(options,function(err,data){
                     if(data){
                         req.flash('error',res.__('warn').e_order);
                         return res.redirect('back');
                     }
                     if(calendarDate.state==1){
                         req.flash('error',res.__('warn').e2_order);
                         return res.redirect('back');
                     }
                     callback(err);
                 })
             },
             function(callback){
                 orderRecord.findOrderRecordByOptions({orderCalendar:req.query.orderCalendar},function(err,data){
                     if(!data){
                         new Calendar().updateById(req.query.orderCalendar,{color:'yellow'},function(error){
                             callback(error);
                         })
                     }else{
                         callback(err);
                     }
                 })
             },
             function(callback){
                 orderRecord.save(function(err){
                     callback(err);
                 })
             },
             function(callback){
                 new Calendar().updateOrderTotalById(req.query.orderCalendar,1,function(err){
                     callback(err);
                 })
             }
         ], function (err) {
             if(err){
                 req.flash('error',res.__('warn').e_data);
             }else{
                 req.flash('success',res.__('warn').s_order);
             }
             return res.redirect('back');
         });
     })
     app.get('/orderList',function(req,res){
         var page = new Page(req.query.num);
         var obj = {
             page: page,
             search: {orderUser:req.query.id?req.query.id:req.session.user._id}
         };

         //同步执行 OrderRecord（预约记录）——》 日程记录表 --》 用户表
//         new OrderRecord().findForPage(obj,function(err,count,pageCount,datas){
//             if(err){
//                 console.log(err);
//             }
//             var users=[];
//             if(datas){
//                 datas.forEach(function(data,index){
//                     var id=data.orderCalendar.user;
//                     new User().findUserById(id,function(err,doc){
//                         if(err){
//                             console.log(err);
//                         }
//                         if(doc){
//                             users.push(doc)
//                             console.log(users)
//                         }
//                     })
//                     console.log(users)
//                 })
//             }
//             console.log('a')
//             console.log(users);
//         })
         async.waterfall([
             function(callback){//查询预约记录
                 new OrderRecord().findForPage(obj, function (err,count, pageCount, datas) {
                     callback(err, count,pageCount,datas);
                 })
             }

         ], function (err, count,pageCount,datas) {
             if(err){
                 req.flash('error', err);
                 return res.redirect('back');
             }else{
                 page.pageCount = pageCount;
                 res.render('orderList', {
                     title: '预约列表',
                     datas: datas,
                     page: page,
                     menu: ''
                 });
             }
         });
     })
     app.get('/meetList',function(req,res){
         var page = new Page(req.query.num);
         var id=req.query.id?req.query.id:req.session.user._id;
         var obj = {
             page: page,
             search: {"$or" : [{"orderToUser" : id}, {"orderUser" : id}],state:1}
         };
         new OrderRecord().findForPage(obj,function (err,count, pageCount, datas){
             if(err){
                 req.flash('error', err);
                 return res.redirect('back');
             }
             page.pageCount = pageCount;
             //var meetDatas=[];
             datas.forEach(function(data,index){
                 if(data.orderToUser._id==id){
                     data.meetData=data.orderUser;
                     data.uname=data.orderToUser.nickname
                 }else{
                     data.meetData=data.orderToUser;
                     data.uname=data.orderUser.nickname
                 }
             })
             //console.log(meetDatas);
             //datas.meetDatas=meetDatas;
             res.render('meetList', {
                 title: '预约列表',
                 id:id,
                 datas: datas,
                 page: page,
                 menu: ''
             });
         })
     })
     app.get('/cancelOrder',function(req,res){
         async.waterfall([
             function(callback){
                 new OrderRecord().findOrderRecordById(req.query.id,function(err,data){
                     callback(err,data.orderCalendar);
                 })
             },
             function(id,callback){
                 new OrderRecord().delOrderRecordById(req.query.id,function(err){
                     callback(err,id);
                 })
             },
             function(id, callback){
                 new Calendar().updateOrderTotalById(id,-1,function(err){
                     callback(err,id);
                 })

             },
             function(id,callback){
                 new OrderRecord().findOrderRecordByOptions({orderCalendar:id},function(err,data){
                     if(!data){
                         new Calendar().updateById(id,{color:'green',state:0},function(error){
                             callback(error);
                         })
                     }else{
                         callback(err);
                     }
                 })
             }
         ], function (err) {
             if(err){
                 req.flash('error', err);
             }else{
                 req.flash('success','取消成功')
             }
             return res.redirect('back');
         });
     })
     app.get('/changOrderState',function(req,res){
         var color;
         if(req.query.state==1){
             color='red';
             state=1;
         }else{
             color='yellow';
             state=2;
         }
         async.waterfall([
             function(callback){
                 new OrderRecord().findOrderRecordById(req.query.id,function(err,data){
                     callback(err,data);
                 })

             },
             function(data,callback){
                 new Calendar().updateById(data.orderCalendar,{color:color,state:state},function(err){
                     callback(err);
                 })

             },
             function(callback){
                 new OrderRecord().changState(req.query.id,req.query.state,function(err){
                        callback(err);
                 })
             }
         ], function (err) {
             if(err){
                 req.flash('error',res.__('warn').e_data)
             }else{
                 req.flash('success',res.__('warn').s_orderstate)
             }
             res.redirect('back')
         });


     })
     app.get('/myOrderList',function(req,res){
         var page = new Page(req.query.num);
         var obj = {
             page: page,
             search: {orderToUser:req.query.id?req.query.id:req.session.user._id}
         };
         new OrderRecord().findForPage(obj,function(err,count,pageCount,datas){
             if(err){
                 req.flash('error', err);
                 return res.redirect('back');
             }
             page.pageCount=pageCount;
             res.render('myOrderList',{
                 title:'我的预约',
                 datas:datas,
                 page:page,
                 menu:''
             })
         })

     })
     app.post('/orderReply',function(req,res){
         var orderReply=new OrderReply();
         orderReply.replyOrder=req.body.replyOrder;
         orderReply.replyMessage=req.body.replyMessage;
         orderReply.save(function(err){
             if(err){
                 req.flash('error', err);
             }else{
                 req.flash('success', '回复成功');
             }
             return res.redirect('back');
         })
     })
     app.get('/findOrderReply',function(req,res){
         var options={replyOrder:req.query.replyOrder}
         new OrderReply().findOrderReplyByOptions(options,function(err,datas){
             if(err){
                 req.flash('error', res.__('warn').e_data);
             }
             res.render('findOrderReply',{
                datas:datas
             })
         })

     })
     app.get('/test', function (req, res) {
         res.render('test01', {
             title:'测试',
             menu:''
         })
     })
     app.post('/addSchedule', function (req, res) {
         var calendar = new Calendar();
         calendar.user = req.session.user._id;
         calendar.title = req.body.title;
         if(req.body.isallday){
             calendar.start=req.body.start;
             if(req.body.isend){
                 calendar.end=req.body.end;
             }
         }else{
             calendar.start=req.body.start+'T'+req.body.s_hour+':'+req.body.s_minute+':00';
             if(req.body.isend){
                 calendar.end=req.body.end+'T'+req.body.e_hour+':'+req.body.e_minute+':00';
             }
         }
         calendar.save(function (err) {
             if (err) {
                 return res.end(res.__('warn').e_data)
             }
             res.render('res');
         })
     })
     app.get('/delSchedule', function (req, res) {
         new OrderRecord().delOrderRecordBySid(req.query.id,function(err){
             if (err) {
                 return res.end(res.__('warn').e_data)
             }
             new Calendar().removeCalendarById(req.query.id, function (err) {

                 if (err) {
                     return res.end(res.__('warn').e_data)
                 }
                 res.render('res');
             })
         })
     });

     app.post('/updSchedule', function (req, res) {
         var calendar = new Calendar();
         calendar.user = req.session.user._id;
         calendar.title = req.body.title;
         if(req.body.isallday){
             calendar.start=req.body.start;
             if(req.body.isend){
                 calendar.end=req.body.end;
             }
         }else{
             calendar.start=req.body.start+'T'+req.body.s_hour+':'+req.body.s_minute+':00';
             if(req.body.isend){
                 calendar.end=req.body.end+'T'+req.body.e_hour+':'+req.body.e_minute+':00';
             }
         }
         new Calendar().removeCalendarById(req.body._id, function (err) {

             if (err) {
                 return res.end(res.__('warn').e_data)
             }
             calendar.save(function (err) {
                 if (err) {
                     return res.end(res.__('warn').e_data)
                 }
                 res.render('res');
             })
         })



     });
     app.get('/partnerDynimic', function (req, res) {
         var page = new Page(req.query.num);
         var obj = {
             page: page,
             search: {user:{"$ne":req.session.user._id}}
         };
         async.waterfall([
             function(callback){
                 new Dynimic().findForPage(obj,function(err,count,pageCount, datas){
                     callback(err,count,pageCount,datas)
                 })
             },
             function(count, pageCount, datas,callback){
                 var i = 0;
                 async.whilst(
                     function () { return i < datas.length; },
                     function (callback) {
                         var options={replyDynimic:datas[i]._id}
                         new DynimicReply().findDynimicReplyByOptions(options,function(err,replyDatas){
                             datas[i].replyDatas=replyDatas;
                             i++;
                             callback();
                         })
                     },
                     function (err) {
                         callback(err,count,pageCount,datas)
                     }
                 );
             }
         ], function (err,count,pageCount,datas) {
             if (err) {
                 req.flash('error', err);
                 return res.redirect('back');
             }
             page.pageCount = pageCount;
             res.render('partnerDynimic', {
                 title: '语伴动态',
                 datas:datas,
                 page:page,
                 menu: 'menu1'
             });
         });
     })
     app.get('/myDynimic',function(req,res){
         var page = new Page(req.query.num);
         var obj = {
             page: page,
             search: {user:req.session.user._id}
         };
         async.waterfall([
             function(callback){
                 new Dynimic().findForPage(obj,function(err,count,pageCount, datas){
                    callback(err,count,pageCount,datas)
                 })
             },
             function(count, pageCount, datas,callback){
                 var i = 0;
                 async.whilst(
                     function () { return i < datas.length; },
                     function (callback) {
                         var options={replyDynimic:datas[i]._id}
                         new DynimicReply().findDynimicReplyByOptions(options,function(err,replyDatas){
                             datas[i].replyDatas=replyDatas;
                             i++;
                             callback();
                         })
                     },
                     function (err) {
                         callback(err,count,pageCount,datas)
                     }
                 );
             }
         ], function (err,count,pageCount,datas) {
             if (err) {
                 req.flash('error', err);
                 return res.redirect('back');
             }
             page.pageCount = pageCount;
             res.render('myDynimic', {
                 title: '我的动态',
                 datas:datas,
                 page:page,
                 menu: 'menu1'
             });
         });
     })
     app.post('/addDynimic',function(req,res){
         var dynimic=new Dynimic();
         dynimic.content=req.body.content;
         dynimic.user=req.session.user._id;
         dynimic.save(function(err){
             if(err){
                 req.flash('error', err);
             }else{
                 req.flash('success','发表成功');
             }
             return res.redirect('back');
         })
     })
     app.post('/replyDynimic',function(req,res){
         var dynimicReply=new DynimicReply();
         dynimicReply.content=req.body.content;
         dynimicReply.replyDynimic=req.body.replyDynimic;
         dynimicReply.user=req.session.user._id;
         dynimicReply.save(function(err){
             if(err){
                 req.flash('error', err);
             }else{
                 req.flash('success','回复成功');
             }
             return res.redirect('back');
         })
     })
     app.get('/delDynimicReply',function(req,res){
         new DynimicReply().delDynimicReplyById(req.query.id,function(err){
             if(err){
                 req.flash('error', err);
             }else{
                 req.flash('success','删除成功');
             }
             return res.redirect('back');
         })
     })
     app.get('/delDynimic',function(req,res){
         async.waterfall([
             function(callback){
                 new Dynimic().delDynimicById(req.query.id,function(err){
                     callback(err);
                 })
             },
             function(callback){
                 var options={replyDynimic:req.query.id};
                 new DynimicReply().delDynimicReplyByOpt(options,function(err){
                     callback(err);
                 })
             }
         ], function (err) {
             if(err){
                 req.flash('error', err);
             }else{
                 req.flash('success','删除成功');
             }
             return res.redirect('back');
         });

     })
     app.all('/findPartner', function (req, res) {
         var page = new Page(req.query.num);
         page.limit=24;
         page.skipFrom=(page.limit*page.num)-page.limit;
         var options={username:{"$ne":req.session.user.username}};
         if(!req.query.keyword==''){
             options.$or=[{username:req.query.keyword},{nickname:req.query.keyword}]
         }
         if(!req.query.language==''){
             options.language=req.query.language;
         }
         if(!req.query.studylanguage==''){
             options.studylanguage=req.query.studylanguage;
         }
         if(!req.query.nowcity==''){
             options.nowcity=req.query.nowcity;
         }
         if(!req.query.country==''){
             options.country=req.query.country;
         }
         switch (req.query.gender){
             case '1':
                 options.gender=1;
                 break;
             case '0':
                 options.gender=0;
                 break;
         }
         switch (req.query.age){
             case '1':
                 options.age={"$gte" :0, "$lte" : 17};
                 break;
             case '2':
                 options.age={"$gte" :18, "$lte" : 22};
                 break;
             case '3':
                 options.age={"$gte" :23, "$lte" : 26};
                 break;
             case '4':
                 options.age={"$gte" :27, "$lte" : 35};
                 break;
             case '5':
                 options.age={"$gt":35};
                 break;
         }
         var obj = {
             page: page,
             search: options
         };
         new User().findForPage(obj, function (err,count, pageCount, datas) {
             if (err) {
                 req.flash('error', err);
                 return res.redirect('back');
             }
             datas.age=req.query.age;
             datas.gender=req.query.gender;
             page.pageCount = pageCount;
             new BbsPlate().findAllPlate(function(err,languageDatas){
                 if(err){
                     req.flash('error', err);
                     return res.redirect('back');
                 }
                 res.render('findPartner', {
                     title: res.__('title').par_find,
                     datas: datas,
                     languagess:languageDatas,
                     page: page,
                     menu: 'menu1'
                 });
             })

         })

     })
     app.post('/addPartner', function (req, res) {
         if(req.body.respondentUser==req.session.user._id){
             req.flash('error','你不能加自己为好友');
             return res.redirect('back');
         }
         var relative = new Relative();
         relative.applyUser = req.session.user._id;        //不知道为什么不能直接存user？？？
         relative.respondentUser = req.body.respondentUser;
         relative.applyMessage = req.body.applyMessage;
         var options1 = {applyUser: req.session.user._id, respondentUser: req.body.respondentUser}
         var options2 = {applyUser: req.body.respondentUser, respondentUser: req.session.user._id}
         if (req.body.replaceApply) {
             relative.deleteByOption(options1, function (err) {
                 if (err) {
                     req.flash('error', err);
                     return res.redirect('back');
                 }
                 relative.save(function (err) {
                     if (err) {
                         req.flash('error', err);
                         res.redirect('back');
                     }
                     req.flash('success', '重新申请成功，等待对方处理');
                     res.redirect('back');
                 })
             })
         } else {
             relative.findByRelative(options2, function (err, data) {
                 if (err) {
                     req.flash('error', err);
                     return res.redirect('back');
                 }
                 if (data) {


                     relative.updateFlagById(data._id, {applyFlag: 1}, function (err) {
                         if (err) {
                             req.flash('error', err);
                             return res.redirect('back');
                         }
                     })
                     relative.applyFlag = 1;
                 }
                 relative.findByRelative(options1, function (err, data) {
                     if (err) {
                         req.flash('error', err);
                         return res.redirect('back');
                     }
                     if (data) {
                         if (data.applyFlag == 0) {
                             req.flash('error', '你已经申请，请等待对方处理');
                             return res.redirect('back');
                         } else if (data.applyFlag == 1) {
                             req.flash('error', '你们已经成为好友，请到我的语伴查看');
                             return res.redirect('back');
                         } else if (data.applyFlag == 2) {
                             req.flash('error', '该用户拒绝添加你为好友，如需要再次添加，请转到语伴申请记录再次申请');
                             return res.redirect('back');
                         }
                     }
                     relative.save(function (err) {
                         if (err) {
                             req.flash('error', err);
                             res.redirect('back');
                         }
                         if (relative.applyFlag == 1) {
                             req.flash('success', '添加好友成功');
                         } else {
                             req.flash('success', '申请已成功，等待对方处理');
                         }
                         return res.redirect('back');
                     })
                 })
             })

         }

     })
     app.get('/applyPartner', function (req, res) {
         var page = new Page(req.query.num);
         var keyword='applyUser';
         var obj = {
             page: page,
             search: {respondentUser: req.session.user._id}
         };
         new Relative().findForPage(obj, keyword,function (err,count, pageCount, datas) {
             if (err) {
                 req.flash('error', err);
                 return res.redirect('back');
             }
             page.pageCount = pageCount;
             res.render('applyPartner', {
                 title: '语伴申请',
                 datas: datas,
                 page: page,
                 menu: 'menu1'
             });
         })


     })
     app.get('/myApply', function (req, res) {
         var page = new Page(req.query.num);
         var keyword='respondentUser';
         var obj = {
             page: page,
             search: {applyUser: req.session.user._id}
         };
         new Relative().findForPage(obj, keyword,function (err,count, pageCount, datas) {
             if (err) {
                 req.flash('error', err);
                 return res.redirect('back');
             }
             page.pageCount = pageCount;
             res.render('myApply', {
                 title: '我的申请',
                 datas: datas,
                 page: page,
                 menu: 'menu1'
             });
         })
     })
     app.get('/disposeApply', function (req, res) {
         var options = {applyFlag: req.query.flag};
         new Relative().updateFlagById(req.query.id, options, function (err) {
             if (err) {
                 req.flash('error', err);
                 return res.redirect('/applyPartner');
             }
             if (req.query.flag == 1) {
                 req.flash('success', '你们已经成功成为好友');
             } else {
                 req.flash('success', '你已成功拒绝添加好友');
             }
             return res.redirect('/applyPartner');
         })
 })
     app.get('/myPartner', function (req, res) {
         var options = {'$or': [
             {applyUser: req.session.user._id},
             {respondentUser: req.session.user._id}
         ], applyFlag: 1};
         var keyword = 'applyUser respondentUser';
         var docs = [];
         var page = new Page(req.query.num);
         var obj = {
             page: page,
             search: options
         };
         new Relative().findForPage(obj,keyword,function (err,count, pageCount, datas) {
             if (err) {
                 req.flash('error', err);
                 return res.redirect('back');
             }
             if (datas) {
                 datas.forEach(function (data, index) {
                     if (req.session.user._id == data.applyUser._id) {
                         docs.push(data.respondentUser);
                     } else {
                         docs.push(data.applyUser);
                     }
                 })
             }
             //为数组添加数据去重的方法
             Array.prototype.distinct = function () {
                 var a = [], b = [];
                 for (var prop in this) {
                     var d = this[prop];
                     if (d === a[prop]) continue; //防止循环到prototype
                     if (b[d] != 1) {
                         a.push(d);
                         b[d] = 1;
                     }
                 }
                 return a;
             }
             docs = docs.distinct();//数据去重
             page.pageCount = pageCount;
             res.render('myPartner', {
                 title: '我的语伴',
                 datas: docs,
                 page: page,
                 menu: 'menu1'
             });
         })
     })
     app.get('/removeRelative', function (req, res) {
         var options = {'$or': [
             {applyUser: req.session.user._id, respondentUser: req.query.id},
             {applyUser: req.query.id, respondentUser: req.session.user._id}
         ]};
         new Relative().deleteByOption(options, function (err) {
             if (err) {
                 req.flash('error', err);
             } else {
                 req.flash('success', '你已经成功解除与该好友的关系')
             }
             return res.redirect('/myPartner');
         })


     })
     app.get('/forumEntry',function(req,res){
         var page=new Page(req.query.num);
         var options={state:0}
         if(req.query.language&&req.query.language.length!=24&&req.query.language!=''){
             req.flash('error',res.__('warn').e_no);
             return res.redirect('/forumEntry');
         }
         if(req.query.language){
             options.bbsPlate=req.query.language;
         }
         if(req.query.search){
             var regex = new RegExp(req.query.search, 'i');
             options.theme=regex;
         }
         var obj={
             page:page,
             search:options
         };
         async.waterfall([
             function(callback){
                 new Post().findForPage(obj,function(err,count,pageCount,datas){
                     callback(err,count,pageCount,datas);
                 })
             },
             function(count,pageCount,datas,callback){
                 var options={'publishUser':{$ne:req.session.user._id}};
                 new Post().findActiveApplyGroup(options,function(err,groupDatas){
                     console.log(groupDatas)
                     callback(err,count,pageCount,datas,groupDatas);
                 })
             },
             function(count,pageCount,datas,groupDatas,callback){
                 var options={_id:{$in:groupDatas}};
                 new User().findUserByOpt(options,function(err,users){
                     callback(err,count,pageCount,datas,users);
                 })
             },
             function(count,pageCount,datas,users,callback){
                 new BbsPlate().findAllPlate(function(err,plateDatas){
                     callback(err,count,pageCount,datas,users,plateDatas);
                 })
             },
             function(count,pageCount,datas,users,plateDatas,callback){
                 new Post().findHotPosts(function(err,hotPosts){
                     callback(err,count,pageCount,datas,users,plateDatas,hotPosts);
                 })
             }
         ], function (err,count,pageCount,datas,users,plateDatas,hotPosts) {
             if(err){
                 req.flash('error',res.__('warn').e_data);
                 return res.redirect('back');
             }
             page.pageCount=pageCount;
             var users1=[];
             users.forEach(function(user,index){
                 if(user._id!=req.session.user._id){
                     users1.push(user)
                 }
             })
             users1.sort(function(){return 0.5-Math.random()})
             res.render('forumEntry',{
                 title:res.__('title').bbs,
                 datas:datas,
                 page:page,
                 users:users1,
                 count:count,
                 plateDatas:plateDatas,
                 language:req.query.language,
                 hotPosts:hotPosts,
                 menu:'menu3'
             })
         });

     })
     app.get('/post',function(req,res){
         new BbsPlate().findAllPlate(function(err,datas){
             if(err){
                 req.flash('error',res.__('warn').e_data);
                 return res.redirect('back');
             }
             res.render('post',{
                 title:res.__('title').post,
                 datas:datas,
                 menu:'menu3'
             })
         })
     })
     app.post('/post', function (req, res) {
         var post = new Post();
         post.publishUser = req.session.user._id;
         post.bbsPlate = req.body.bbsPlate;
         post.theme = req.body.theme;
         post.postDate=new Date();
         post.content =req.body.content;
         post.save(function (err,data) {
             if (err) {
                 req.flash('error',res.__('warn').e_data);
                 return res.redirect('back');
             }
             new BbsPlate().updatePostTotalById(req.body.bbsPlate, function (err) {
                 if (err) {
                     req.flash('error',res.__('warn').e_data);
                     return res.redirect('back');
                 }
                 req.flash('success',res.__('warn').s_post);
                 res.redirect('/postParticulars?id='+data._id);
             })

         });
     })
     app.get('/postParticulars',function(req,res){
         var page=new Page(req.query.num);
         var options={}
         var obj={
             page:page,
             search:options
         };
         async.waterfall([
             function(callback){
                 new Post().updateHitTotalById(req.query.id,function(err){
                     callback(err);
                 })
             },
             function(callback){
                 new Post().findPostById(req.query.id,function(err,data){
                     callback(err,data);
                 })
             },
             function(data,callback){
                 new BbsPlate().updateHitsById(data.bbsPlate._id,function(err){
                     callback(err,data);
                 })
             },
             function(data,callback){
                 obj.search={replyPost:data._id};
                 new Reply().findForPage(obj,function(err,count,pageCount,replyDatas){
                     callback(err,count,pageCount,replyDatas,data);
                 })
             },
             function(count,pageCount,replyDatas,data,callback){
                 var i = 0;

                 async.whilst(
                     function () { return i < replyDatas.length; },
                     function (callback) {
                         new SecondReply().findSecondReplyByOption({toReply:replyDatas[i]},function(err,secondReplyDatas){
                             replyDatas[i].secondReplys=secondReplyDatas;
                             i++;
                             callback();
                         })
                     },
                     function (err) {
                         callback(err,count,pageCount,replyDatas,data);
                     }
                 );

             },
             function(count,pageCount,replyDatas,data,callback){
                 var options={'publishUser':{$ne:req.session.user._id}};
                 new Post().findActiveApplyGroup(options,function(err,groupDatas){
                     callback(err,count,pageCount,replyDatas,data,groupDatas);
                 })
             },
             function(count,pageCount,replyDatas,data,groupDatas,callback){
                 var options={_id:{$in:groupDatas}};
                 new User().findUserByOpt(options,function(err,users){
                     callback(err,count,pageCount,replyDatas,data,users);
                 })
             }
         ], function (err,count,pageCount,replyDatas,data,users) {
             if(err){
                 req.flash('error',res.__('warn').e_data);
                 return res.redirect('/forumEntry');
             }
             page.pageCount=pageCount;
             var users1=[];
             users.forEach(function(user,index){
                 if(user._id!=req.session.user._id){
                     users1.push(user)
                 }
             })
             users1.sort(function(){return 0.5-Math.random()})
             res.render('postParticulars',{
                 title:res.__('title').p_post,
                 replyDatas:replyDatas,
                 page:page,
                 users:users1,
                 count:count,
                 data:data,
                 menu:'menu3'
             })
         });
     })
     app.post('/reply',function(req,res){
         var reply=new Reply();
//         if(req.body.replyFlag){
//             reply.toUser=req.body.userId;
//             reply.toReply=req.body.replyId;
//         }
         reply.replyPost=req.body.id;
         reply.replyUser=req.session.user._id;
         reply.content=req.body.content;
         reply.save(function(err){
             if(err){
                 req.flash('error',res.__('warn').e_data);
                 return res.redirect('back');
             }
             new Post().updateReplyTotalById(req.body.id,function(err){
                 if(err){
                     req.flash('error',res.__('warn').e_data);
                 }else{
                     req.flash('success',res.__('warn').s_reply)
                 }
                 return res.redirect('back');
             })

         })
     })
     app.post('/secondReply',function(req,res){
         var secondReply=new SecondReply();
         secondReply.secondReplyUser=req.session.user._id;
         secondReply.toUser=req.body.userId;
         secondReply.toReply=req.body.replyId;
         secondReply.content=req.body.content;
         secondReply.save(function(err){
             if(err){
                 req.flash('error',res.__('warn').e_data);
                 return res.redirect('back');
             }
             new Reply().updateSecondReplyTotalById(req.body.replyId,function(err){
                 if(err){
                     req.flash('error',res.__('warn').e_data);
                 }else{
                     req.flash('success',res.__('warn').s_reply)
                 }
                 return res.redirect('back');
             })

         })
     })
     app.get('/active',function(req,res){
         var page=new Page(req.query.num);
         var options={state:1}
         if(req.query.language){
             options.language=req.query.language;
         }
         var obj={
             page:page,
             search:options
         };
         async.waterfall([
             function(callback){
                 new Active().findForPage(obj,function(err,count,pageCount,datas){
                     callback(err,count,pageCount,datas);
                 })
             },
             function(count, pageCount, datas,callback){
                 var i = 0;
                 async.whilst(
                     function () { return i < datas.length; },
                     function (callback) {
                         var options={user:req.session.user._id,applyActive:datas[i]._id}
                         new ActiveApply().findActiveApplyByOptions(options,function(err,applyDatas){
                             if(applyDatas.length==0){
                                 datas[i].applyState=3;
                             }else{
                                 datas[i].applyState=applyDatas[0].state;
                             }
                             i++;
                             callback();
                         })
                     },
                     function (err) {
                         callback(err,count,pageCount,datas)
                     }
                 );
             },
             function(count,pageCount,datas,callback){
                 var options={'user':{$ne:req.session.user._id}};
                 new ActiveApply().findActiveApplyGroup(options,function(err,groupDatas){
                     callback(err,count,pageCount,datas,groupDatas);
                 })
             },
             function(count,pageCount,datas,groupDatas,callback){
                 var options={_id:{$in:groupDatas}};
                 new User().findUserByOpt(options,function(err,users){
                     callback(err,count,pageCount,datas,users);
                 })
             },
             function(count,pageCount,datas,users,callback){
                 new BbsPlate().findAllPlate(function(err,plateDatas){
                     callback(err,count,pageCount,datas,users,plateDatas);
                 })
             },
             function(count,pageCount,datas,users,plateDatas,callback){
                 new ActiveToPost().findDatasByGroup({},function(err,hotActives){
                     console.log(hotActives)
                     callback(err,count,pageCount,datas,users,plateDatas,hotActives);
                 })
             },
             function(count,pageCount,datas,users,plateDatas,hotActives,callback){
                 var options={_id:{$in:hotActives}};
                 new Active().findActiveByOpt(options,function(err,hotActives){
                     console.log(hotActives)
                     callback(err,count,pageCount,datas,users,plateDatas,hotActives);
                 })
             }
         ], function (err,count,pageCount,datas,users,plateDatas,hotActives) {
             if(err){
                 req.flash('error',res.__('warn').e_data);
                 return res.redirect('back');
             }
             page.pageCount=pageCount;
             var users1=[];
             users.forEach(function(user,index){
                 if(user._id!=req.session.user._id){
                     users1.push(user)
                 }
             })
             users1.sort(function(){return 0.5-Math.random()})//打乱顺序
             res.render('active',{
                 title:res.__('title').active,
                 datas:datas,
                 page:page,
                 users:users1,
                 count:count,
                 plateDatas:plateDatas,
                 hotActives:hotActives,
                 language:req.query.language,
                 menu:'menu2'
             })
         });

     })
     app.get('/activeParticulars',function(req,res){
         async.waterfall([
             function(callback){
                 new Active().findActiveById(req.query.id,function(err,data){
                     if(!data){
                         req.flash('error',res.__('warn').e_data);
                         return res.redirect('/active');
                     }
                     callback(err,data);
                 })
             },
             function(data, callback){
                 var options={'user':{$ne:req.session.user._id}};
                 new ActiveApply().findActiveApplyGroup(options,function(err,groupDatas){
                     console.log(groupDatas)
                     callback(err,data,groupDatas);
                 })
             },
             function(data,groupDatas,callback){
                 var options={_id:{$in:groupDatas}};
                 new User().findUserByOpt(options,function(err,users){
                     callback(err,data,users);
                 })
             },
             function(data, users,callback){
                 new ActiveToPost().findDatasByActive(req.query.id,function(err,relatePosts){
                     callback(err,data,users,relatePosts);
                 })
             },
             function(data, users,relatePosts,callback){
                 var array=[];
                 relatePosts.forEach(function(relatePost,index){
                     array.push(relatePost.post);
                 })
                 new Post().findPostByRelate({_id:{$in:array}},function(err,relatePosts){
                     callback(err,data,users,relatePosts);
                 })
             }
         ], function (err,data,users,relatePosts) {
             if(err){
                 req.flash('error',res.__('warn').e_data);
                 return res.redirect('/active');
             }
             var users1=[];
             users.forEach(function(user,index){
                 if(user._id!=req.session.user._id){
                     users1.push(user)
                 }
             })
             users1.sort(function(){return 0.5-Math.random()})
             res.render('activeParticulars',{
                 title:res.__('title').p_active,
                 data:data,
                 users:users1,
                 relatePosts:relatePosts,
                 menu:'menu2'
             })
         });
     })
     app.get('/applyActive',function(req,res){
         var options={user:req.session.user._id,applyActive:req.query.id};
         var activeApply=new ActiveApply();
         activeApply.user=req.session.user._id;
         activeApply.applyActive=req.query.id;
         async.waterfall([
             function(callback){
                 new Active().findActiveById(req.query.id,function(err,data){
                     var now =new Date();
                     console.log(dateFormat(now,'yyyy-mm-dd'))
                     if(data.activeDate<=dateFormat(now,'yyyy-mm-dd')){

                         req.flash('error',res.__('warn').e_timeout);
                         //return res.send('已过期')
                         return res.redirect('back');
                     }
                     callback()

                 })
             },
             function(callback){
                 activeApply.findActiveApplyByOptions(options,function(err,datas){
                     callback(err,datas);
                 })
             },
             function(datas, callback){
                 if(datas.length!=0){
                       req.flash('error',res.__('warn').e_active);
                       return res.redirect('back');
                 }

                 activeApply.save(function(err){
                         callback(err);
                 })
             },

             function(callback){
                 new Active().updateApplyNum(req.query.id,1,function(err){
                     callback(err);
                 })
             }
         ], function (err, result) {
             if(err){
                  req.flash('error',res.__('warn').e_data);
             }else{
                  req.flash('success',res.__('warn').s_active)
             }
             return res.redirect('back');
         });

//         var id=req.query.id;
//         var applyId=req.session.user._id;
//         Array.prototype.contains = function (element) {
//             for (var i = 0; i < this.length; i++) {
//                 if (this[i] == element) {
//                     return true;
//                 }
//             }
//             return false;
//         }
//         new Active().findActiveById(id,function(err,data){
//             if(err){
//                 req.flash('error','没有该活动');
//                 return res.redirect('back');
//             }
//             if(data.applyUsers.contains(applyId)){
//                 req.flash('error','你已经申请该活动');
//                 return res.redirect('back');
//             }
//             new Active().applyActive(id,applyId,function(err){
//                 if(err){
//                     req.flash('error',err);
//                 }else{
//                     req.flash('success','申请成功')
//                 }
//                 return res.redirect('back');
//             })
//         })

     })
     app.get('/loveActive',function(req,res){
         var options={user:req.session.user._id,active:req.query.id};
         var loveActive=new LoveActive();
         loveActive.user=req.session.user._id;
         loveActive.active=req.query.id;
         loveActive.findLoveActiveByOptions(options,function(err,datas){
             if(err){
                 req.flash('error',res.__('warn').e_data);
                 return res.redirect('back');
             }
             if(datas.length!=0){
                 req.flash('error',res.__('warn').el_active)
                 return res.redirect('back');
             }
             loveActive.save(function(err){
                 if(err){
                     req.flash('error',res.__('warn').e_data);
                 }else{
                     req.flash('success',res.__('warn').sl_active);
                 }
                 return res.redirect('back');

             })
         })

     })
     app.get('/myLoveActive',function(req,res){
         var page=new Page(req.query.num);
         var obj={
             page:page,
             search:{user:req.query.id?req.query.id:req.session.user._id}
         };

         new LoveActive().findForPage(obj,function(err, count,pageCount, datas){
             if(err){
                 req.flash('error',res.__('warn').e_data)
                 return res.redirect('back');
             }
             page.pageCount=pageCount
             res.render('myLoveActive',{
                 datas:datas,
                 page:page
             })
         })
     })
     app.get('/addActive',function(req,res){
         req.session.user.poster=null;
         new BbsPlate().findAllPlate(function(err,datas){
             if(err){
                 req.flash('error',res.__('warn').e_data);
                 return res.redirect('back');
             }
             res.render('addActive',{
                 title:'发布活动',
                 menu:'menu2',
                 plateDatas:datas
             })
         })

     })
     app.post('/uploadPoster',function(req,res){
         if (req.files.file.size == 0){
             // 使用同步方式删除一个文件
             req.session.user.poster=null;
             fs.unlinkSync(req.files.file.path);//当上传文件没有选择时也会生成图片，所以需要删除
             //req.flash('error', '你没有上传文件!');
             //res.redirect('back');
             res.end(res.__('warn').e1_upload);
         } else if(req.files.file.type.split('/')[0]!='image'){
             req.session.user.poster=null;
             fs.unlinkSync(req.files.file.path);//当上传文件没有选择时也会生成图片，所以需要删除
//             req.flash('error', '上传文件无效!');
//             res.redirect('back');
             res.end(res.__('warn').e2_upload);
         }else{
             //console.log(req.files.file)
             //fs.rename(req.files.file.path,'public/images/test/'+req.files.file.name);
             var word=req.files.file.path.replace('public','');
             req.session.user.poster=word;
             //req.session.auser.poster='123123';
             //res.redirect('back');
             var data = '{url:'+'"'+encodeURIComponent(word)+'"'+',state:"上传成功"}';
             //var data = {url:word,state:"上传成功"};
             res.end(data);
         }
     })
     app.post('/addActive',function(req,res){
         if(!req.session.user.poster){
             req.flash('error', res.__('warn').e3_upload);
             return res.redirect('back');
         }
         var active=new Active();
         active.poster=req.session.user.poster;
         active.user=req.session.user._id;
         active.sponsor=req.body.sponsor;
         active.activeDate=req.body.activeDate;
         active.addr=req.body.addr;
         active.theme=req.body.theme;
         active.discribe=req.body.discribe;
         active.language=req.body.language;
         active.cost=req.body.cost;
         active.save(function(err){
             if(err){
                 req.flash('error',res.__('warn').e_data);
             }else{
                 req.flash('success',res.__('warn').s2_upload);
                 req.session.user.poster=null;
             }
             res.redirect('/active');
         })

     })
     app.get('/myActive',function(req,res){
         var page=new Page(req.query.num);
         var options={user:req.query.id?req.query.id:req.session.user._id}
//         page.limit=2;
//         page.skipFrom=(page.limit*page.num)-page.limit;
         var obj={
             page:page,
             search:options
         };

         new ActiveApply().findForPage(obj,function(err,count,pageCount, datas){
             if(err){
                 req.flash('error',res.__('warn').e_data);
                 return res.redirect('back');
             }
             page.pageCount = pageCount;
             res.render('myActive',{
                 datas:datas,
                 page:page
             })
         })
     })
     app.get('/forgetPassword',function(req,res){
         res.render('forgetPassword',{
             title:'密码找回',
             menu:'menu2'
         })
     })
     app.post('/forgetPassword',function(req,res){
         new User().findUserByName(req.body.username,function(err,data){
             if(err){
                 req.flash('error','系统繁忙，请稍后再试');
                 return res.redirect('back');
             }
             if(data){
                 var email=data.email;
                 var email2='';
                 for(var i=0;i<email.length;i++){
                     if(email.charAt(i)=='@'){
                         for(var j=i;j<email.length;j++){
                             email2+=email.charAt(j);
                         }
                         break;
                     }
                     if(i<4){
                         email2+=email.charAt(i);
                     }else{
                         email2+='*';
                     }
                 }
                 return res.render('forgetPassword_2',{
                     title:'密码找回',
                     username:data.username,
                     email:email2,
                     menu:'menu2'
                 })
             }
             req.flash('error','用户名不存在,你不会忘记用户名了吧？');
             return res.redirect('back');

         })


     })
     app.get('/sendEmail',function(req,res){
         new User().findUserByName(req.query.username,function(err,data){
             if(err){
                 req.flash('error','系统繁忙，请稍后再试');
                 return res.redirect('/');
             }
             if(data){
                 var smtpTransport=nodemailer.createTransport("SMTP",{
                     host:"smtp.126.com",//主机  qq：smtp.qq.com
                     secureConnection:true,//使用ssl
                     port:465,//smtp端口  ssl:465
                     auth:{
//                         user:"likechat2014@126.com",
//                         pass:"lovelikechat"
                         user:"likechat2014@126.com",
                         pass:"lovelikechat"
                     }
                 })
                 var overtime=new Date().getTime()+1000*60*60;           //过期时间
                 var md5 = crypto.createHash('md5');
                 var key =encodeURIComponent(md5.update(data.username+overtime).digest('base64')) ;
                 new User().updateUserById(data._id,{overtime:overtime},function(err){
                     if(err){
                         req.flash('error','系统繁忙，请稍后再试');
                         return res.redirect('back');
                     }
                     var html='';
                     html+='亲爱的用户'+data.username+'：您好！<br><br>';
                     html+='        您收到这封这封电子邮件是因为您 (也可能是某人冒充您的名义) 申请了一个新的密码。假如这不是您本人所申请, 请不用理会<br>这封电子邮件, 但是如果您持续收到这类的信件骚扰, 请您尽快联络管理员。<br><br>';
                     html+='        要使用新的密码, 请使用以下链接启用密码。<br><br>';
                     html+='http://115.28.90.45:3000/resetPassword?username='+data.username+'&sid='+key+'<br>';
                     html+=' (如果无法点击该URL链接地址，请将它复制并粘帖到浏览器的地址输入框，然后单击回车即可。该链接更改密码成功后将失效。)<br>'
                     html+=' 注意:请您在收到邮件1个小时内('+dateFormat(overtime, "yyyy-mm-dd HH:MM:ss")+'前)使用，否则该链接将会失效。'
                     html+='<br><br>我们将一如既往、热忱的为您服务！';
                     html+='<br><br>http://115.28.90.45:3000/ - 中国最大的coffee社区，为你提供最全面的信息传播和服务平台';
                     var mailOptions = {
                         from: "service <likechat2014@126.com>", // 发件地址
                         to: data.email, // 收件列表
                         subject: "[爱聊网]找回你的账号密码", // 标题
                         html: html // html 内容
                     }
                     smtpTransport.sendMail(mailOptions,function(err,response){
                         if(err){
                             console.log('连接错误！！！')
                             console.log(err);
//                             req.flash('error','邮箱不存在？未知错误，请查看邮箱是否有效');
//                             return res.redirect('/');
                         }
//                         console.log(response.message);
                         smtpTransport.close();//关闭连接
                     })
                     return res.render('forgetPassword_3',{
                         title:'密码找回',
                         menu:'menu2'
                     })
                 })

             }else{
                 req.flash('error','用户名不存在,你不会忘记用户名了吧？');
                 return res.redirect('/');
             }

         })

     })
     app.get('/resetPassword',function(req,res){
         new User().findUserByName(req.query.username,function(err,data){
             if(err){
                 req.flash('error','系统繁忙，请稍后再试');
                 return res.redirect('/forgetPassword');
             }
             if(data){
                 var overtime=data.overtime;
                 if(overtime<=new Date().getTime()){
                     req.flash('error','链接已经过期，请重新申请找回密码');
                     return res.redirect('/forgetPassword');
                 }
                 var md5 = crypto.createHash('md5');
                 var key = md5.update(data.username+overtime).digest('base64');
                 console.log(key);
                 console.log(req.query.sid);
                 if(key!=req.query.sid){
                     req.flash('error','链接不正确，已经过期了吧,重新申请吧');
                     return res.redirect('/forgetPassword');
                 }
                 res.render('forgetPassword_4',{
                     title:'找回密码',
                     menu:'menu2'
                 })
             }else{
                 req.flash('error','连接错误，无法找到匹配用户，请重新申请找回密码');
                 return res.redirect('/forgetPassword');
             }

         })

     })
     app.post('/resetPassword',function(req,res){
         if (req.body['password-repeat'] != req.body['password']) {
             req.flash('error', '两次输入的口令不一致');
             return res.redirect('back');
         }
         var md5 = crypto.createHash('md5');
         var password = md5.update(req.body.password).digest('base64');
         new User().updateUserByName(req.query.username,{password:password,overtime:0},function(err){
             if(err){
                 req.flash('error','更改失败,请稍后再试');
                 return res.redirect('/forgetPassword');
             }
             req.flash('success','修改密码成功');
             return res.redirect('/');
         })

     })
     app.get('/mycenter',function(req,res){
         var user=new User();
         var options={username:{"$nin":[req.session.user.username]}};
         async.waterfall([
             function(callback){
                 user.findUserByOpt(options,function(err,recommendUsers){//所有用户
                     recommendUsers.sort(function(){return 0.5-Math.random()})
                     if(recommendUsers.length<=10){
                         res.render('mycenter',{
                             title:res.__('title').mycenter,
                             recommendUsers:recommendUsers,
                             menu:''
                         })
                     }else{
                         callback(err);
                     }
                 })
             },
             function(callback){
                 options.nowcity=req.session.user.nowcity;//居住地
                 user.findUserByOpt(options,function(err,recommendUsers){
                     recommendUsers.sort(function(){return 0.5-Math.random()})
                     if(recommendUsers.length<=10){
                         res.render('mycenter',{
                             title:res.__('title').mycenter,
                             recommendUsers:recommendUsers,
                             menu:''
                         })
                     }else{
                         callback(err);
                     }
                 })
             },
             function(callback){
                 options.country=req.session.user.country;//国籍
                 user.findUserByOpt(options,function(err,recommendUsers){
                     if(recommendUsers.length<=10){
                         recommendUsers.sort(function(){return 0.5-Math.random()});
                         res.render('mycenter',{
                             title:res.__('title').mycenter,
                             recommendUsers:recommendUsers,
                             menu:''
                         })
                     }else{
                         callback(err);
                     }
                 })
             },
             function(callback){
                 if(req.session.user.age>=0&&req.session.user.age<=17){//年龄
                     options.age={"$gte" :0, "$lte" : 17};
                 }else if(req.session.user.age>=18&&req.session.user.age<=22){
                     options.age={"$gte" :18, "$lte" : 22};
                 }else if(req.session.user.age>=23&&req.session.user.age<=26){
                     options.age={"$gte" :23, "$lte" : 26};
                 }else if(req.session.user.age>=27&&req.session.user.age<=35){
                     options.age={"$gte" :27, "$lte" : 35};
                 }else{
                     options.age={"$gt":35};
                 }
                 user.findUserByOpt(options,function(err,recommendUsers){
                     if(recommendUsers.length<=10){
                         recommendUsers.sort(function(){return 0.5-Math.random()})
                         res.render('mycenter',{
                             title:res.__('title').mycenter,
                             recommendUsers:recommendUsers,
                             menu:''
                         })
                     }else{
                         callback(err);
                     }
                 })
             },
             function(callback){
                 options.gender=data.gender;//性别
                 user.findUserByOpt(options,function(err,recommendUsers){
                     if(recommendUsers.length<=10){
                         recommendUsers.sort(function(){return 0.5-Math.random()})
                         res.render('mycenter',{
                             title:res.__('title').mycenter,
                             recommendUsers:recommendUsers,
                             menu:''
                         })
                     }else{
                         callback(err,recommendUsers);
                     }
                 })
             }

         ], function (err,recommendUsers) {
             if(err){
                 req.flash('error',res.__('warn').e_data);
                 return res.redirect('back');
             }
             recommendUsers.sort(function(){return 0.5-Math.random()});
             recommendUsers.length=10;
             res.render('mycenter',{
                 title:res.__('title').mycenter,
                 recommendUsers:recommendUsers,
                 menu:''
             })

         });
     })
     app.get('/editMyData',function(req,res){
         new BbsPlate().findAllPlate(function(err,datas){
             res.render('editMyData',{
                 title:res.__('title').editdata,
                 datas:datas,
                 menu:''
             })
         })

     })
     app.post('/editMyData',function(req,res){
         var options={
             nickname:req.body.nickname,
             email:req.body.email,
             gender:req.body.gender,
             age:req.body.age,
             country:req.body.country,
             describe:req.body.describe,
             wechat:req.body.wechat,
             nowcity:req.body.nowcity,
             language:req.body.language,
             studylanguage:req.body.studylanguage
         }
         new User().updateUserById(req.session.user._id,options,function(err){
             if(err){
                 req.flash('error',res.__('warn').e_data);
                 return res.redirect('/mycenter');
             }else{
                 new User().findUserByName(req.session.user.username,function(err,data){
                     if(err){
                         req.flash('error',res.__('warn').e_data);
                     }else{
                         req.flash('success',res.__('warn').s_editMyData);
                         req.session.user=data;
                     }
                     return res.redirect('/mycenter');
                 })
             }
         })
     })
     app.post('/uploadHead',function(req,res){
         console.log(req.files.file.path)
         if (req.files.file.size == 0){
             // 使用同步方式删除一个文件

             fs.unlinkSync(req.files.file.path);//当上传文件没有选择时也会生成图片，所以需要删除
             req.flash('error', res.__('warn').e1_upload);
             res.redirect('back');
         } else if(req.files.file.type.split('/')[0]!='image'){
             fs.unlinkSync(req.files.file.path);//当上传文件没有选择时也会生成图片，所以需要删除
             req.flash('error', res.__('warn').e2_upload);
             res.redirect('back');
         }else {
//             var md5 = crypto.createHash('md5');
//             var array=req.files.file.name.split('.');
//             var name = md5.update(new Date().getTime()+'').digest('base64');
//             var target_path = './public/images/user_img/' + name+'.'+array[array.length-1];
//             var headSrc='/images/user_img/'+name+'.'+array[array.length-1];
             // 使用同步方式重命名一个文件
             //fs.renameSync(req.files.file.path, target_path);

             //console.log('Successfully renamed a file!');
             if(req.session.user.headSrc.indexOf('man')<0){
                 fs.unlinkSync('./public'+req.session.user.headSrc);
             }
             new User().updateUserById(req.session.user._id,{headSrc:req.files.file.path.replace('public','')},function(err){
                 if(err){
                     req.flash('error', res.__('warn').e_data);
                 }else{
                     req.flash('success',res.__('warn').s_upload);
                 }
                 req.session.user.headSrc=req.files.file.path.replace('public','');
                 res.redirect('back');


             })

         }
     })
     app.get('/partnerCenter',function(req,res){
         var user=new User();
         var options={username:{"$nin":[req.query.username,req.session.user.username]}};
         async.waterfall([
             function(callback){
                 user.findUserByName(req.query.username,function(err,data){
                     callback(err,data);
                 })
             },
             function(data,callback){
                 user.findUserByOpt(options,function(err,recommendUsers){//所有用户
                     recommendUsers.sort(function(){return 0.5-Math.random()})
                     if(recommendUsers.length<=10){
                         res.render('partnerCenter',{
                             title:res.__('title').p_center,
                             data:data,
                             recommendUsers:recommendUsers,
                             menu:'menu1'
                         })
                     }else{
                         callback(err,data);
                     }
                 })
             },
             function(data, callback){
                 options.nowcity=data.nowcity;//居住地
                 user.findUserByOpt(options,function(err,recommendUsers){
                     recommendUsers.sort(function(){return 0.5-Math.random()})
                     if(recommendUsers.length<=10){
                         res.render('partnerCenter',{
                             title:res.__('title').p_center,
                             data:data,
                             recommendUsers:recommendUsers,
                             menu:'menu1'
                         })
                     }else{
                         callback(err,data);
                     }
                 })
             },
             function(data, callback){
                 options.country=data.country;//国籍
                 user.findUserByOpt(options,function(err,recommendUsers){
                     recommendUsers.sort(function(){return 0.5-Math.random()})
                     if(recommendUsers.length<=10){
                         recommendUsers.sort(function(){return 0.5-Math.random()})
                         res.render('partnerCenter',{
                             title:res.__('title').p_center,
                             data:data,
                             recommendUsers:recommendUsers,
                             menu:'menu1'
                         })
                     }else{
                         callback(err,data);
                     }
                 })
             },
             function(data, callback){
                 if(data.age>=0&&data.age<=17){//年龄
                     options.age={"$gte" :0, "$lte" : 17};
                 }else if(data.age>=18&&data.age<=22){
                     options.age={"$gte" :18, "$lte" : 22};
                 }else if(data.age>=23&&data.age<=26){
                     options.age={"$gte" :23, "$lte" : 26};
                 }else if(data.age>=27&&data.age<=35){
                     options.age={"$gte" :27, "$lte" : 35};
                 }else{
                     options.age={"$gt":35};
                 }
                 user.findUserByOpt(options,function(err,recommendUsers){
                     if(recommendUsers.length<=10){
                         recommendUsers.sort(function(){return 0.5-Math.random()})
                         res.render('partnerCenter',{
                             title:res.__('title').p_center,
                             data:data,
                             recommendUsers:recommendUsers,
                             menu:'menu1'
                         })
                     }else{
                         callback(err,data);
                     }
                 })
             },
             function(data, callback){
                 options.gender=data.gender;//性别
                 user.findUserByOpt(options,function(err,recommendUsers){
                     if(recommendUsers.length<=10){
                         recommendUsers.sort(function(){return 0.5-Math.random()})
                         res.render('partnerCenter',{
                             title:res.__('title').p_center,
                             data:data,
                             recommendUsers:recommendUsers,
                             menu:'menu1'
                         })
                     }else{
                         callback(err,data,recommendUsers);
                     }
                 })
             }
         ], function (err, data,recommendUsers) {
             if(err){
                 req.flash('error',res.__('warn').e_data);
                 return res.redirect('back');
             }
             recommendUsers.sort(function(){return 0.5-Math.random()});
             recommendUsers.length=10;
             res.render('partnerCenter',{
                 title:res.__('title').p_center,
                 data:data,
                 recommendUsers:recommendUsers,
                 menu:'menu1'
             })

         });
     })
     app.get('/partner_Schedule',function(req,res){
         new User().findUserByName(req.query.username,function(err,data){
             if(err){
                 req.flash('error',res.__('warn').e_data);
                 return res.redirect('back');
             }
             res.render('partnerSchedule',{
                 data:data
             });
         })

     })
     app.get('/about',function(req,res){
         res.render('about',{
             title:res.__('title').about,
             menu:''
         })
     })
     app.get('/event',function(req,res){

         res.render('event',{
             date:req.query.date.substring(0,10)
         })
     })
     app.get('/editEvent',function(req,res){
         res.render('editEvent',{
             title:req.query.title,
             start:req.query.start.substring(0,10),
             end:req.query.end?req.query.end.substring(0,10):req.query.start.substring(0,10),
             _id:req.query._id,
             display:req.query.end?"display:inline":"display:none",
             checked:req.query.end?'aaa':'',
             color:req.query.color
         })
     })
     app.get('/json',function(req,res){
         var options={start:{$gte:req.query.start,$lte:req.query.end},user: req.session.user._id}
         new Calendar().findCalendarByOpt(options,function(err,datas){
               console.log(datas.length);
               res.render('json',{
                   datas:datas
               });
//             var str="[{title:'测试',start:'2014-09-24}]";
//             res.end(str);
         })
     })
     app.get('/myPost',function(req,res){
         var page=new Page(req.query.num);
         var obj={
             page:page,
             search:{publishUser:req.query.id?req.query.id:req.session.user._id}
         };

         new Post().findForPage(obj,function(err, count,pageCount, datas){
             if(err){
                 req.flash('error',res.__('warn').e_data)
                 return res.redirect('back');
             }
             page.pageCount=pageCount
             res.render('myPost',{
                 datas:datas,
                 page:page
             })
         })
     })
     app.get('/myReplyPost',function(req,res){
         var page=new Page(req.query.num);
         var obj={
             page:page,
             search:{replyUser:req.query.id?req.query.id:req.session.user._id}
         };

         new Reply().findForPage(obj,function(err, count,pageCount, datas){
             if(err){
                 req.flash('error',res.__('warn').e_data)
                 return res.redirect('back');
             }
             page.pageCount=pageCount
             res.render('myReplyPost',{
                 datas:datas,
                 page:page
             })
         })
     })
     app.get('/coffee',function(req,res){
         console.log(req.query.id)
         new Coffee().findCoffeeById(req.query.id,function(err,data){
             if(err){
                 req.flash('error',res.__('warn').e_data)
                 return res.redirect('back');
             }
             res.render('coffee',{
                 title:res.__('title').coffee,
                 data:data,
                 menu:'menu1'
             })
         })
     })
 };

